<template>
    <div class="company-user-list" v-show="isShow">
        <ul class="global-operation-list">
            <li class="global-operation-left">
                <ul class="global-filter-list">
                    <li class="global-filter-item">
                        <el-button type="primary" class="global-filter-item-search" v-if="operationList.includes('add')"
                            @click="add">添加</el-button>
                    </li>
                </ul>
            </li>
        </ul>
        <div class="global-table-content">
            <div class="global-table-content-a">
                <el-table :data="dataList" style="width: 100%" 
                    :row-style="{height: '0'}"
                    :cell-style="{padding: '3px'}"
                    max-height="620" border
                v-loading="tableLoading">
                    <el-table-column prop="date" label="时间">
                    </el-table-column>
                    <el-table-column prop="totalPrice" label="总价值">
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template slot-scope="scope">
                            <div>
                                <el-button @click="handleView(scope.row)" type="text" size="small">查看</el-button>
                            </div>
                            <div>
                                <el-button @click="handleExport(scope.row)" type="text" size="small">导出</el-button>
                            </div>
                            <div v-if="operationList.includes('del')">
                                <el-button @click="handleDel(scope.row)" type="text" size="small">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="global-page">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :page-sizes="pageSizes" :page-size="pageSize" :current-page="pageNum" background
                        layout="sizes, total, prev, pager, next" :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>

        
        <el-dialog title="导入" :visible.sync="addDialog" width="45%">
            <div style="display: flex;text-align: center; align-items: center;">
                <div style="width: 100px">
                    月份：
                </div>
                <div style="padding-left: 10px;">
                    <el-date-picker
                        v-model="chooseTime"
                        type="month"
                        placeholder="选择月">
                    </el-date-picker>
                </div>
            </div>
            <div style="display: flex;text-align: center; align-items: center; padding-top: 20px;">
                <div style="width: 100px">
                    文件：
                </div>
                <div style="padding-left: 10px;">
                    <el-upload
                        class="upload-demo"
                        drag
                        :action="url"
                        :on-progress="uploadFileLoading"
                        :data="{ token: $store.state.token }"
                        :headers="{ 'Access-Control-Allow-Origin': '*' }"
                        :show-file-list="false"
                        :http-request="checkedFile">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialog = false">取 消</el-button>
                <!-- <el-button type="primary" @click="submit">确 定</el-button> -->
            </div>
        </el-dialog>

        
        <el-dialog title="详情" :visible.sync="msgDialog" width="65%">
            <div>
                <div style="display: flex;">
                    <div>
                        <el-input v-model="chooseUserTypeName" clearable placeholder="请输入用户类型名称"></el-input>
                    </div>
                    <div style="padding-left: 10px;">
                        <el-select v-model="chooseUserType" clearable placeholder="请选择用户类型">
                            <el-option
                            v-for="item in userTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div style="padding-left: 20px;">
                        <el-button type="primary" plain @click="getMsgList">搜索</el-button>
                    </div>
                </div>
                <div class="global-table-content">
                    <div class="global-table-content-a">
                        <el-table :data="msgDataList" style="width: 100%" 
                    :row-style="{height: '0'}"
                    :cell-style="{padding: '3px'}"
                    max-height="620" border
                        v-loading="msgTableLoading">
                            <el-table-column prop="username" label="用户名称">
                            </el-table-column>
                            <el-table-column prop="area" label="地区">
                            </el-table-column>
                            <el-table-column prop="payPrice" label="工资">
                            </el-table-column>
                            <el-table-column prop="userType" label="用户类型">
                                <template slot-scope="scope">
                                    <div>
                                        {{ scope.row.userType == 1 ? '商务' : '其他' }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="userTypeName" label="用户类型名称">
                            </el-table-column>
                        </el-table>
                        <div class="global-page">
                            <el-pagination @current-change="handleCurrentChangeMsg"
                                :page-size="msgPageSize" :current-page="msgPageNum" background
                                layout="total, prev, pager, next" :total="msgTotal">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import API from "@/api/apiPayRoll";
import qs from "qs";
import axios from "axios";
export default {
    name: "PayRollList",
    props: {
        operationList: Array,
        isShow: Boolean,
    },
    watch: {
        isShow(val) {
            if (val) {
                this.getPost()
            }
        },
    },
    data() {
        return {
            // 表格相关
            tableLoading: true,
            dataList: [],
            pageSize: 10,
            pageNum: 1,
            total: 0,
            pageSizes: [5, 10, 15, 20],
            tokenData: {
                token: "",
            },
            searchForm: {
                keyword: null,
                cateIds: null,
                areaId: null,
                businessId: null,
                executionProgressId: null,
                arrivalProgressId: null,
                arrivalWarehouseId: null,
                status: null,
            },
            dialogFormVisible: false,
            form: {
                projectId: null,
                projectName: '',
                brands: '',
                brandsUsername: '',
                cateIdList: [],
                bussinessUsername: '',
                areaIds: [],
                permissionUsername: '',
            },
            formLabelWidth: '120px',
            dialogTitle: '新增',
            userInfo: {},
            addDialog: false,
            chooseTime: null,
            url: '',
            uploadLoading: false,
            msgDialog: false,
            msgPageNum: 1,
            msgDataList: [],
            msgTableLoading: false,
            msgTotal: 0,
            userTypeOptions: [
                {
                    label: '商务',
                    value: 1,
                }, 
                {
                    label: '其他',
                    value: 10,
                }
            ],
            chooseUserType: null,
            chooseUserTypeName: '',
            msgPageSize: 10,
        };
    },
    activated() {
        // this.url = "https://checkorder.mejour.cn/checkorder/manager/pc/user/importExcelPayRoll?token=" + this.$store.state.token
        // this.url = "http://localhost:9003/checkorder/manager/pc/user/importExcelPayRoll?token=" + this.$store.state.token
        //this.url = process.env.VUE_APP_REQUSET_URL + "/checkorder/manager/pc/user/importExcelPayRoll?token=" + this.$store.state.token;
        this.url = `/checkorder/manager/pc/user/importExcel?token=${this.$store.state.token}`;
        this.tokenData.token = this.$store.state.token;
        this.userInfo = JSON.parse(localStorage.getItem("mujinguserInfo"))
        this.getPost()
    },
    mounted() {
        this.tokenData.token = this.$store.state.token
    },
    methods: {
        handleDel(row){
            this.$confirm('确认删除该条数据吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.handleDelPost(row.time)
            })
        },
        handleDelPost(time) {
            this.tableLoading = true;
            const params = {
                token: this.$store.state.token,
                time: time
            };
            API.doDelPayRollMonth(params).then((res) => {
                if (res.key === 1000) {
                    this.$message({
                        message: "删除成功",
                        type:'success'
                    });
                    this.getPost()
                }
            });
        },
        add(){
            this.chooseTime = null
            this.addDialog = true
        },
        handleView(row){
            this.chooseTime = row.time
            this.chooseUserType = null
            this.chooseUserTypeName = ''
            this.msgPageNum = 1
            this.msgDataList = []
            this.msgTotal = 0
            this.getMsgList();
            this.msgDialog = true
        },
        handleCurrentChangeMsg(e) {
            this.msgPageNum = e;
            this.getMsgList();
        },
        getMsgList(){
            this.msgTableLoading = true;
            const params = {
                token: this.$store.state.token,
                pageNum: this.msgPageNum,
                pageSize: 10,
                time: this.chooseTime
            };
            if(this.chooseUserType){
                params.userType = this.chooseUserType
            }
            if(this.chooseUserTypeName){
                params.userTypeName = this.chooseUserTypeName
            }
            API.getPayRollMonthList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.msgTotal = res.count;
                    res.list.forEach(item => {
                        if (item.time) {
                            item.date = this.formatterDate(item.time)
                        }
                    })
                    this.msgDataList = res.list;
                    this.msgTableLoading = false;
                }
            });
        },
        checkedFile(obj){
            let that = this
            if(!this.chooseTime){
                this.$message({
                    type: "error",
                    message:  "请选择月份",
                });
                return;
            }
            let url = this.url;
            const formData = new FormData();
            formData.append( "file" , obj.file );//file 和 后端字段要保持一致
            formData.append("token", this.$store.state.token)
            formData.append("time", this.chooseTime.getTime())
            const config = {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    token: this.$store.state.token
                },
                timeout: 1000 * 60 * 10 //这里2分钟内的配置是生效的，超过了就不行。。
            };
            const loading = this.$loading({
                lock: true,
                text: '导入中，若数据量过大，则时间较长，在此期间请勿操作，请等待......',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            return axios.post(url, formData,config)
                .then((rs) => {
                    console.log(rs)
                    if (rs.status ===200){
                        console.log(rs.data)
                        let data = rs.data
                        if ( data.key === 1000 ){
                            that.$message.success({
                                showClose: true,
                                message: "上传成功",
                                duration: 1500
                            });
                            this.addDialog = false
                            that.getPost()
                        }else {
                            that.$message({
                                type: "warning",
                                message: rs.data.message,
                            });
                        }
                    }else {
                        that.$message({
                            type: "warning",
                            message: rs,
                        });
                    }
                    loading.close();
                    })
                    .catch( (rs) => {
                        loading.close();
                        this.$message({
                            type: "error",
                            message:  rs,
                        });
                    });
        },
        uploadFileLoading(e){
            this.uploadLoading = true
        },
        formatterDate(time) {
            return this.$moment(time).format("YYYY-MM");
        },
        formatterTime(time) {
            return this.$moment(time).format("YYYY-MM-DD HH:mm:ss");
        },
        // 全局初始化
        init() {
            // 搜索条件重置
            this.searchForm = {
                keyword: null,
                cateIds: null,
                areaId: null,
                businessId: null,
                executionProgressId: null,
                arrivalProgressId: null,
                arrivalWarehouseId: null,
                status: null,
            };
            this.rePosts();
        },
        // 分页pageSize改变
        handleSizeChange(e) {
            this.pageSize = e;
            this.rePosts();
        },
        // 分页pageNum改变
        handleCurrentChange(e) {
            this.pageNum = e;
            this.getPost();
        },
        // 重新请求
        rePosts() {
            this.pageNum = 1;
            this.dataList = [];
            this.getPost();
        },
        // 表格列表
        getPost() {
            this.tableLoading = true;
            const params = {
                token: this.$store.state.token,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            };
            API.getPayRollList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.total = res.count;
                    res.list.forEach(item => {
                        if (item.time) {
                            item.date = this.formatterDate(item.time)
                        }
                    })
                    this.dataList = res.list;
                    this.tableLoading = false;
                }
            });
        },
        // 导出
        handleExport(row) {
            if(!this.dataList || this.dataList.length <= 0){
                this.$message({
                    type: 'error',
                    message: '无工资表可以进行导出'
                });
                return
            }
            this.tableLoading = true;
            const params = {
                token: this.$store.state.token,
                time: row.time
            };
            API.doExportPayRoll(params).then((res) => {
                if (res) {
                    const content = res.data;
                    const blob = new Blob([content]);
                    // 从response的headers中获取filename,
                    // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
                    var contentDisposition = res.headers["content-disposition"];
                    var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
                    var result = patt.exec(contentDisposition);
                    const fileName = decodeURI(result[1]);
                    this.tableLoading = false;
                    if ("download" in document.createElement("a")) {
                        // 非IE下载
                        const elink = document.createElement("a");
                        elink.download = fileName;
                        elink.style.display = "none";
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href); // 释放URL 对象
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, fileName);
                    }
                }
            });
        },
    },
};
</script>

<style lang="sass">
.avatar-uploader
    .el-upload
      border: 1px dashed #d9d9d9
      border-radius: 6px
      cursor: pointer
      position: relative
      overflow: hidden
      &:hover
        border-color: #409eff
      .avatar-uploader-icon
        font-size: 28px
        color: #8c939d
        width: 100px
        height: 100px
        line-height: 100px !important
        text-align: center
      .avatar
        width: 100px
        height: 100px
        display: block
</style>
<style lang="sass" scoped>
.global-operation-list
  padding-left: 0
.global-select .global-select-btn
  background: #FFFFFF
.global-table-content
  padding: 0
  background-color: white
  width: 100%
.global-table-content-a
  margin: 0 auto
  width: 90%
  padding: 20px 0
.company-user-list
  //@include container
  .isStatus1
    width: 41px
    height: 21px
    background: #F1FFFC
    border-radius: 3px
    border: 1px solid #03C192
    font-size: 14px!important
    color: #03C192!important
    line-height: 21px
    text-align: center
  .isStatus2
    width: 41px
    height: 21px
    background: #FFF2F2
    border-radius: 3px
    border: 1px solid #F46565
    font-size: 14px!important
    color: #F44141!important
    line-height: 21px
    text-align: center
  .global-operation-left
    margin-right: 0
  ::v-deep .permission-dialog
    .el-dialog__body
      display: flex
      align-items: center
      flex-direction: column
      padding: 30px 60px
      .permission-dialog-tree
        width: 100%
        max-height: 450px
        overflow-y: auto
        overflow-x: hidden
        margin-bottom: 40px
  .global-table
    display: flex
    align-items: center
    justify-content: center
    flex-direction: column
    .list
      background: #FFFFFF
      box-shadow: 0px 0px 10px 0px rgba(93, 139, 198, 0.05)
      border-radius: 14px
      margin-bottom: 15px
      width: 100%
      display: flex
      align-items: center
      justify-content: space-between
      padding: 19px 24px
      .left
        display: flex
        align-items: center
        .img
          width: 90px
          height: 90px
          border-radius: 4px
          margin-right: 17px
        .nav
          .text1
            font-size: 20px
            font-weight: bold
            color: #222222
            line-height: 26px
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 16px
            span
              height: 16px
              background: #FFF8ED
              border-radius: 11px
              border: 1px solid #FF9901
              font-size: 12px
              color: #FF9901
              line-height: 16px
              padding: 0 8px
              display: block
              text-align: center
              margin-left: 11px
          .text2
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 25px
            i
              font-size: 20px
              color: #1861FD
              margin-right: 7px
            .text2_1
              font-size: 14px
              color: #222222
              line-height: 19px
              margin-right: 7px
            .text2_2
              margin-left: 5px
              font-size: 23px
              font-weight: bold
              color: #222222
              line-height: 29px
              margin-right: 3px
            .text2_3
              font-size: 14px
              color: #B5B5C3
              line-height: 19px
          .text3
            display: flex
            align-items: center
            i
              font-size: 14px
              color: #B5B5C3
              margin-right: 5px
            div
              font-size: 14px
              color: #B5B5C3
              line-height: 19px
              margin-right: 80px
      .right
//.permission-dialog-item
//  background: #f2f2f2

</style>
